package io.boot.modules.msg.service.impl;

import io.boot.modules.msg.entity.MsgInfoEntity;
import io.boot.modules.sys.entity.SysUserEntity;
import io.boot.modules.sys.service.SysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.boot.common.utils.PageUtils;
import io.boot.common.utils.Query;

import io.boot.modules.msg.dao.MsgInfoDeptDao;
import io.boot.modules.msg.entity.MsgInfoDeptEntity;
import io.boot.modules.msg.service.MsgInfoDeptService;


@Service("msgInfoDeptService")
public class MsgInfoDeptServiceImpl extends ServiceImpl<MsgInfoDeptDao, MsgInfoDeptEntity> implements MsgInfoDeptService {

    @Autowired
    private SysDeptService sysDeptService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MsgInfoDeptEntity> page = this.page(
                new Query<MsgInfoDeptEntity>().getPage(params),
                new QueryWrapper<MsgInfoDeptEntity>()
                .in((List<Long>) params.get("list")!=null,"create_by",(List<Long>) params.get("list"))
        );

        return new PageUtils(page);
    }


    @Override
    public void saveOrUpdate(MsgInfoEntity msgInfo, SysUserEntity user) {
        //        1.部门数据权限 2.部门及以下数据权限 3.自定义数据权限
        List<Long> deptList=new ArrayList<>();
        if (msgInfo.getMsgType()==1){
            deptList.add(user.getDeptId());
        }else if(msgInfo.getMsgType()==2){
            List<Long> deptLists=sysDeptService.byDeptGetDeptChild(user.getDeptId());
            deptList.addAll(deptLists);
        }
        if(msgInfo.getMsgType()!=3){
            msgInfo.setDeptIdList(deptList);
        }

        //先删除角色与菜单关系
        deleteBatch(new Long[]{msgInfo.getMsgInfoId()});
        if(msgInfo.getDeptIdList().size() == 0){
            return ;
        }
        //保存角色与菜单关系
        for(Long deptId : msgInfo.getDeptIdList()){
            MsgInfoDeptEntity msgInfoDeptEntity=new MsgInfoDeptEntity();
            msgInfoDeptEntity.setDeptId(deptId);
            msgInfoDeptEntity.setMsgInfoId(msgInfo.getMsgInfoId());
            this.save(msgInfoDeptEntity);
        }
    }

    @Override
    public List<Long> byMsgInfoGetDeptList(Long msgInfoId) {
        return baseMapper.byMsgInfoGetDeptList(msgInfoId);
    }

    private int deleteBatch(Long[] longs) {
       return baseMapper.deleteBatch(longs);
    }

}


